package logic

import (
	"fmt"
	"net/http"
	"strconv"
	"strings"
	"tiktok/dao"
	"tiktok/models"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

type listmsg struct {
	models.Status
	Video_list []videos `json:"video_list"`
}
type videos struct {
	models.Video
}

func ListVideo(ctx *gin.Context) {
	uid := ctx.Query("user_id")
	//token := ctx.Query("token")
	db := dao.GetDB(ctx)
	fmt.Println("//////////////////////////////////////")
	fmt.Println(uid)
	//fmt.Println(token)

	// _, err := web.ParseToken(token)
	// if err != nil { //解析token失败
	// 	logrus.Error("logic,web.ParseToken:解析token失败...")
	// 	ctx.JSON(http.StatusBadRequest,
	// 		models.Status{
	// 			StatusCode: -1,
	// 			StatusMsg:  "服务器内部错误！",
	// 		})
	// 	return
	// }

	var author models.User
	video := make([]videos, 0, 256)
	err := db.Table("tiktok_user").Where("uid = ?", uid).Find(&author).Error //作者信息
	judgeErr(err, ctx, "listvideo:db.select:作者信息查询失败...")

	err = db.Table("tiktok_video").Where("author_id = ?", uid).Find(&video).Error //视频列表
	judgeErr(err, ctx, "listvideo:db.select:视频列表查询失败...")

	type love_videos struct {
		lvideo string `gorm:"love_video"`
	}
	var love_video love_videos
	err = db.Table("tiktok_user").Select("love_video").Where("uid = ?", uid).Find(&love_video.lvideo).Error //喜欢列表
	judgeErr(err, ctx, "listvideo:db.select:喜欢列表查询失败...")

	for i := 0; i < len(video); i++ { //判断是否喜欢
		video[i].Author = author
		str := "/" + strconv.FormatInt(video[i].Vid, 10) + "/"
		if ok := strings.Contains(love_video.lvideo, str); ok {
			video[i].IsFavorite = true
		} else {
			video[i].IsFavorite = false
		}
	}

	ctx.JSON(http.StatusOK, listmsg{
		Status: models.Status{
			StatusCode: 0,
			StatusMsg:  "查询成功!",
		},
		Video_list: video,
	})
}

func judgeErr(err error, ctx *gin.Context, str string) {
	if err != nil {
		logrus.Error(err, str)
		ctx.JSON(http.StatusBadRequest, loginmsg{
			Status: models.Status{
				StatusCode: -1,
				StatusMsg:  "失败",
			},
		})
		return
	}
}
